﻿using Emoney.UserTraining.Model;
using Emoney.UserTraining.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Emoney.UserTraining.Comm;
using Emoney.UserTraining.Cache;
using System.Text;

namespace Emoney.UserTraining.Web.Controllers
{
    public class TrainController : Controller
    {
        
        //
        // GET: /Train/
        //获取软件传的地址解析sso
        GetUserName.UserLoginInfo GetUser(ref Dictionary<string, string> dic,string uid)
        {
            string querystirng = "";
            if (!string.IsNullOrEmpty(Request["token"]))
            {
                querystirng = Request.QueryString.ToString();
            }
            else
            {
                string key = "UserTrainUrlSSO_" + uid;
                News2CacheTools cache = new News2CacheTools();
                object obj = cache.Get<object>(key);
                if (obj != null)
                {
                    querystirng = (string)obj;
                }
            }
            if (!string.IsNullOrEmpty(querystirng))
            {
                string[] arr = querystirng.Split('&');
                foreach (var c in arr)
                {
                    var a2 = c.Split('=');
                    var key = a2.Length > 0 ? a2[0] : "";
                    var value = a2.Length > 1 ? a2[1] : "";
                    if (!dic.ContainsKey(key))
                    {
                        dic.Add(key, value);
                    }
                }
                GetUserName.access access = new GetUserName.access();
                var user = access.GetUserInfo(querystirng, "127.0.0.1", 0);
                if (!string.IsNullOrEmpty(user.UserName))
                {
                    return user;
                }
                else
                {
                    return new GetUserName.UserLoginInfo();
                }
            }
            else
            {
                return new GetUserName.UserLoginInfo();
            }
        }
        public ActionResult Index()
        {
            string actionUrl = Request.QueryString.ToString();
            string uid = Request["uid"];
            string key = "UserTrainUrlSSO_" + uid;

            /******** 2013-06-19 新增方法支持 3位9位pid    begin*********/
            string pid = Request["pid"];
            #region pid升级9位后转3为，做软件3位9位支持
            string newpid = Pub.GetPid_9To3(pid);
            #endregion
            actionUrl = actionUrl.Replace("pid=" + pid, "pid=" + newpid);
            /*****end*****/
            

            News2CacheTools cache = new News2CacheTools();
            object obj = cache.Get<object>(key);
            if (obj != null)
            {
                cache.Remove(key);
            }
            cache.Add(key, actionUrl, 24, 0, 0);
            string ct = Request["clienttype"];
            
            string url = "~/Train/wltrain?uid=" + uid + "&ind=true";
            if (ct == "3" || ct == "15")
            {
                if (pid != "211") {//体验版免费版走老的用户培训通道
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    var c = GetUser(ref dic, uid);
                    emoneybusiness.emoneybusiness ws = new emoneybusiness.emoneybusiness();
                    string rel = ws.check_pay_time(c.UserName);//0:体验期内 1：体验期外
                    if (rel == "2" || rel == "0" || rel == "")//收费版体验期外的用户也走正式培训通道
                    {
                        int ret = ws.EM_IsXeUser_Web(c.UserName);
                        if (ret == 0)//非决策体验15天l2用户走老培训通道（sso原pid=202，clienttype=3)
                        {
                            url = "http://mini.emoney.cn/jrpt/UTrain/wltrain?" + actionUrl;
                        }
                    }
                    else
                    {
                        int ret = ws.EM_IsXeUser_Web(c.UserName);
                        if (ret == 0)//非决策体验15天l2用户走老培训通道（sso原pid=202，clienttype=3)
                        {
                            url = "http://mini.emoney.cn/jrpt/UTrain/wltrain?" + actionUrl;
                        }
                    }
                }
            }
            return Redirect(url);
        }
        public string GetCityName(string areaid)
        {
            string area = "";
            emoneybusiness.emoneybusiness ws = new emoneybusiness.emoneybusiness();
            var tt = ws.GetCityName(OTO.ToStr(areaid, "100000000"));
            if (tt == null)
            {
                area = "上海";
            }
            else
            {
                area = tt.Trim();
            }
            return area;
        }
        /// <summary>
        /// 点击量录入公用方法
        /// </summary>
        /// <param name="typename"></param>
        /// <param name="remark"></param>
        public void AddClickCount(string typename, string remark, string trainid,string uid)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic,uid);
            string ct = dic.ContainsKey("clienttype") ? dic["clienttype"] : "";
            string uname = c.UserName;
            string pid = c.Pid + "_" + ct;
            string areaid = dic.ContainsKey("agentid") ? dic["agentid"] : "";
            string area = GetCityName(areaid);
            
            Training_ClickCountBLL.AddClickCount(uname, area, pid, trainid, typename, remark);
        }
       
        public ActionResult AddClickCount_js()
        {
            string typename = Request["typename"];
            string remark = HttpUtility.UrlDecode(Request["remark"]);
            string trainid = Request["trainid"];
            string uid = Request["uid"];
            AddClickCount(typename, remark, trainid, uid);
            return Content("");
        }
        public ActionResult wltrain()
        {
            string uid = Request["uid"];
            string ind = "false";
            if (!string.IsNullOrEmpty(Request["ind"]))
            {
                ind = "true";
            }
            AddClickCount("wltrain","网络培训页面","",uid);
            ViewBag.uid = uid;
            ViewBag.ind = ind;
            return View();
        }

        public ActionResult dmtrain()
        {
            string uid = Request["uid"];
            AddClickCount("dmtrain", "地面培训页面", "",uid);
            string uname = "";
            string pid = "";
            string areaid = "";
            string area = "上海";
            string trainid = Request["trainid"];
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic,uid);
            List<DmTrain> lst = new List<DmTrain>();
            if (c != null)
            {
                uname = c.UserName;
                pid = c.Pid;
                areaid = dic.ContainsKey("agentid") ? dic["agentid"] : "";

                area = GetCityName(areaid);
            }
            string ct = Request["clienttype"];

            Web_TrainDmBLL m = new Web_TrainDmBLL();
            List<DmTrain> lst1 = new List<DmTrain>();

            lst1 = m.GetTarget(area);
            if (trainid == null)
            {
                trainid = "";
            }
            lst = m.ShowDmTrain(area, trainid);
            ViewData["uname"] = uname;
            ViewData["area"] = area;
            ViewData["dmlist"] = lst;
            ViewData["targetlst"] = lst1;
            ViewData["trainid"] = trainid;
            ViewBag.uid = uid;
            return View();
        }

        public ActionResult alltrain()
        {
            string uid = Request["uid"];
            AddClickCount("alltrain","当月课表页面","",uid);
            ViewBag.uid = uid;
            return View();
        }
        public ActionResult AddOrder()
        {
            string netid = Request["netid"];
            string uid = Request["uid"];
            string uname = "";
            string areaid = "";
            string pid = "";
            string area = "";
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var o = GetUser(ref dic,uid);
            if (o != null)
            {
                uname = o.UserName;
                pid = o.Pid;
                areaid = dic.ContainsKey("agentid") ? dic["agentid"] : "";

                area = GetCityName(areaid);
            }
            Training_MeetingUserBLL bll = new Training_MeetingUserBLL();
            Training_MeetingUser c = new Training_MeetingUser();
            c.uid = uid;
            c.netid = netid;
            c.username = uname;
            c.area = area;
            c.pid = pid;
            c.isOrder = "1";//预约默认1，取消预约为0
            c.Ordertime = DateTime.Now;
            c.addtime = DateTime.Now;
            int rows = bll.AddUser(c);
            //清空提供软件tip数据缓存
            TrainNetwoekAndUserCache uSerCache = new TrainNetwoekAndUserCache();
            uSerCache.Remove(uid);

            //清空我的培训cache缓存
            News2CacheTools ch = new News2CacheTools();
            string key = "mytraindetail_" + uname;
            ch.Remove(key);
            return Content(rows.ToString());
        }

        public ActionResult ModifyOrder()
        {
            string orderid = Request["id"];
            Training_MeetingUserBLL bll = new Training_MeetingUserBLL();
            int rows = bll.ModifyUser(int.Parse(orderid), "1", DateTime.Now);//提前30分钟提醒1，未设置为0或NULL
            return Content(rows.ToString());
        }

        //获取历史培训课程
        public List<VideoEntity> GetHistoryTrain()
        {
            string key = "HistoryTrain";
            List<VideoEntity> videolst = null;
            News2CacheTools cache = new News2CacheTools();
            var obj = cache.Get<List<VideoEntity>>(key);
            if (obj == null)
            {
                string videourl = Config.voteurl;
                string rel = Pub.LoadData(videourl + "video/xyVideoList.ashx?top=3");

                if (!string.IsNullOrEmpty(rel))
                {
                    videolst = JsonConvert.DeserializeObject<List<VideoEntity>>(rel);
                    cache.Add(key, videolst, 1, 0, 0);
                }
            }
            else {
                videolst = obj;
            }
            return videolst;
        }

        public ActionResult lstrain()
        {
            string uid = Request["uid"];
            string str = "";
            AddClickCount("lstrain", "历史培训页面", "", uid);
            //获取会议类型
            Traning_NetworkMeetingBLL tnm = new Traning_NetworkMeetingBLL();
            var lst = tnm.GetAllList().Where(x => x.ddlarea == "全国").Take(4).ToList();

            string key = "lstj_train";
            News2CacheTools cache = new News2CacheTools();
            var obj = cache.Get<string>(key);
            if (obj == null)
            {
                List<Traning_MeetingType> lsttj = new List<Traning_MeetingType>();
                lsttj = tnm.GetMeetingType();
                str = GetTJStr(lsttj);
                cache.Add(key, str, 0, 5, 0);
            }
            else
            {
                str = obj;
            }
            ViewBag.tnm = lst;
            ViewBag.uid = uid;
            ViewBag.tjstr = str;
            return View();
        }
        public ActionResult GetAjaxTJStr()
        {
            return Content("");
        }
        public string GetTJStr(List<Traning_MeetingType> lst)
        {
            Traning_NetworkMeetingBLL bll = new Traning_NetworkMeetingBLL();
            StringBuilder sb = new StringBuilder();
            sb.Append("<table cellpadding='0' cellspacing='0'>");
            sb.Append("<tr>");
            int rel = 0;
            int lstc = lst.Count;
            if (lstc % 2 != 0)
            {
                lstc = lstc + 1;
            }
            if (lst != null)
            {
                for (int i = 0; i < lstc / 2; i++)
                {
                    List<Traning_NetworkMeeting> lstmeet = new List<Traning_NetworkMeeting>();
                    int count = 0;
                    sb.Append("<td>");
                    for (int jnum = rel; jnum < lst.Count; jnum++)
                    {
                        lstmeet = bll.GetMeetByType(lst[jnum].meetingType).ToList();
                        var meet = lstmeet.Take(1).ToList();
                        if (count < 2)
                        {
                            if (lstmeet != null && lstmeet.Count > 0)
                            {
                                string sty = "";
                                if (count == 0)
                                {
                                    sty = "margin-right:10px;";
                                }
                                sb.Append("<div class='item' style='" + sty + "'>");
                                sb.Append("<div class='tit'>" + lst[jnum].meetingType + "</div>");

                                foreach (var c in meet)
                                {
                                    sb.Append("<div class='intro'>");
                                    sb.Append("<div class='head'>");
                                    sb.Append("<img  style='width:64px; height:64px;' src='" + StringTools.GetTeacherImg(c.lecturerImage, 63) + "'/>");//
                                    sb.Append("</div>");
                                    sb.Append("<div class='name1'><b>" + StringTools.SubStr(c.txtteachar, 3) + "</b></div>");
                                    sb.Append("<div class='brief'>");
                                    sb.Append("<b>" + StringTools.SubStr(c.mtg_name, 15) + "</b><br />");
                                    sb.Append(StringTools.SubStr(c.mtg_conent, 55));
                                    sb.Append("</div>");
                                    sb.Append("<div class='btn'>");
                                    sb.Append("<a href='" + c.video_url + "' target='_blank' onclick='AddClickCount('videoTip','课程回放','" + c.Id + "')'>");
                                    sb.Append("<img  state='true' src='" + StringTools.GetStaticFile("Images/Train/images/btn4.jpg") + "'/></a>");// 
                                    sb.Append("</div>");
                                    sb.Append("</div>");
                                }
                                lstmeet = lstmeet.Skip(1).Take(2).ToList();
                                sb.Append("<div class='lesson'>");
                                sb.Append("<div class='tit1'>·同类课程</div>");
                                foreach (var c in lstmeet)
                                {
                                    sb.Append("<div class='list'>");
                                    sb.Append("<div class='text'>《" + StringTools.SubStr(c.mtg_name, 10) + "》" + c.txtteachar + "</div>");
                                    sb.Append("<div class='btn'>");
                                    sb.Append("<a href='" + c.video_url + "' target='_blank'  onclick='AddClickCount('videoTip','课程回放','@c.Id')'>");
                                    sb.Append("<img  state='true' src='" + StringTools.GetStaticFile("Images/Train/images/btn5.jpg") + "'/></a>");// 
                                    sb.Append("</div>");
                                    sb.Append("</div>");
                                }
                                sb.Append("</div>");
                                sb.Append("</div>");
                            }
                        }
                        else { break; }

                        count++;
                        rel++;
                    }
                    sb.Append("</td>");

                }
            }
            sb.Append("</tr>");
            sb.Append("</table>");
            return sb.ToString();
        }
        public ActionResult mytrain()
        {
            string uid = Request["uid"];
            AddClickCount("mytrain", "我的培训页面", "",uid);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic,uid);
            Training_MeetingUserBLL tmubll = new Training_MeetingUserBLL();
            Web_TrainUserBLL wtubll = new Web_TrainUserBLL();
            List<TrainNetwoekAndUser> tmulst = null;
            List<Web_TrainUser> wtulst = new List<Web_TrainUser>();
            if (!string.IsNullOrEmpty(c.UserName))
            {
                wtulst = wtubll.GetListByMonth(c.UserName);
            }
            ViewBag.tmulst = tmulst;
            ViewBag.wtulst = wtulst;
            ViewBag.useneme = c.UserName;
            ViewBag.uid = uid;
            return View();
        }
        public ActionResult mytrainDetail()
        {
            string uid = Request["uid"];
            string url = Request.QueryString.ToString();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic, uid);
            Training_MeetingUserBLL tmubll = new Training_MeetingUserBLL();
            Web_TrainUserBLL wtubll = new Web_TrainUserBLL();
            List<TrainNetwoekAndUser> tmulst = new List<TrainNetwoekAndUser>();
            List<Web_TrainUser> wtulst = new List<Web_TrainUser>();
            if (!string.IsNullOrEmpty(c.UserName))
            {
                wtulst = wtubll.GetListByMonth(c.UserName);
                //tmulst = tmubll.GetLstByUserName(c.UserName).Where(x => Math.Abs((DateTime.Now - x.class_date).Days) < 7).OrderBy(x => x.class_date).ToList();
                //if (tmulst.Count > 8)
                //{
                //    tmulst = tmulst.Take(8).OrderBy(x => x.class_date).ToList();
                //}
                tmulst = tmubll.GetLstByUserName(c.UserName).Where(x => x.class_date.Month == DateTime.Now.Month).OrderBy(x => x.class_date).ToList();
                int page = 1;
                if (!int.TryParse(Request["page"], out page))
                {
                    page = 1;
                }
                int count = tmulst.Count;
                tmulst = tmulst.Skip((page - 1) * 8).Take(8).ToList();
                string strPage = StringTools.PageUrlWeb(count, page, 8, "?" + url);
                ViewData["strPage"] = strPage;
            }
            ViewBag.tmulst = tmulst;
            ViewBag.wtulst = wtulst;
            ViewBag.useneme = c.UserName;
            ViewBag.uid = uid;
            return View();
        }

        public ActionResult ckdmtrain(string trainid)
        {
            string uid = Request["uid"];
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic,uid);
            List<Web_TrainUser> wtulst = new List<Web_TrainUser>();
            Web_TrainUserBLL wtubll = new Web_TrainUserBLL();
            Web_TrainPlaceBLL wtpbll = new Web_TrainPlaceBLL();
            List<Web_TrainPlace> wtplst = new List<Web_TrainPlace>();

            if (!string.IsNullOrEmpty(c.UserName))
            {
                wtulst = wtubll.GetListByMonth(c.UserName);
                wtplst = wtpbll.GetList(c.UserName);

            }
            ViewBag.wtplst = wtplst;
            if (string.IsNullOrEmpty(trainid) && wtplst.Count > 0)
            {
                wtplst = wtplst.Take(1).ToList();
            }
            else
            {
                wtplst = wtplst.Where(x => x.id == Convert.ToInt32( trainid)).ToList();
            }
            ViewBag.wtplstcontent = wtplst;
            ViewBag.username = c.UserName;
            ViewBag.uid = uid;
            return View();
        }
        public ActionResult ModifyUserById(int id, string isOrder,string uid)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic,uid);
            if (c.UserName != null)
            {
                //清空我的培训cache缓存
                var uname = c.UserName;
                News2CacheTools ch = new News2CacheTools();
                string key = "mytraindetail_" + uname;
                ch.Remove(key);
            }
            Training_MeetingUserBLL bll = new Training_MeetingUserBLL();
            int rel = bll.ModifyUserById(id, isOrder);
            TrainNetwoekAndUserCache cache = new TrainNetwoekAndUserCache();
            cache.Remove(uid);
            return Content(rel.ToString());
        }
        public ActionResult wltrainDetail()
        {
            string uid = Request["uid"];
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic,uid);

            string uname = "";
            string pid = "";
            string area = "";
            string areaid = "";
            string ct = Request["clienttype"];
            string Nettype = "0";//(0:无课程 1:进行课程 2:最新课程)
            if (c != null)
            {
                uname = c.UserName;
                pid = c.Pid;
                areaid = dic.ContainsKey("agentid") ? dic["agentid"] : "";

                area = GetCityName(areaid);
            }
            Traning_NetworkMeetingBLL bll = new Traning_NetworkMeetingBLL();
            List<Traning_NetworkMeeting> list = bll.GetNetAll();
            List<Traning_NetworkMeeting> lstOne = new List<Traning_NetworkMeeting>();
            List<Traning_NetworkMeeting> tjLst = new List<Traning_NetworkMeeting>();
            if (list != null && list.Count > 0)
            {
                List<Traning_NetworkMeeting> lstarea = list.Where(x => x.ddlarea == area).Where(x => x.chblist_pro.Contains(pid)).ToList();
                List<Traning_NetworkMeeting> lstqg = list.Where(x => x.ddlarea == "全国").Where(x => x.chblist_pro.Contains(pid)).ToList();
                lstOne = lstarea.Concat(lstqg).OrderBy(x => x.class_date).Take(1).ToList();

                if (lstOne.Count > 0)
                {
                    List<Traning_NetworkMeeting> lstjxz = lstOne.Where(x => x.class_date.AddMinutes(-double.Parse(x.before_time)) < DateTime.Now).ToList();
                    if (lstjxz.Count > 0)
                    {
                        Nettype = "1";//课程正在进行中
                    }
                    else
                    {
                        Nettype = "2";//课程还未开始
                    }
                }
                tjLst = lstarea.Concat(lstqg).Where(x => x.isRecommend == "1").Take(4).ToList();//推荐课程
            }
            
            ViewData["historyLst"] = GetHistoryTrain();//历程课程列表
            ViewData["tjLst"] = tjLst;
            ViewData["area"] = area;
            ViewData["pid"] = pid;  
            ViewData["uname"] = uname;
            ViewData["netType"] = Nettype;
            ViewData["leftLst"] = lstOne;
            ViewBag.uid = uid;
            return View();
        }
       
        public ActionResult alltrainDetail()
        {
            string url = Request.QueryString.ToString();
            string uname = "";
            string pid = "";
            string area = "";
            string areaid = "";
            string uid = Request["uid"];
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic,uid);
            if (c != null)
            {
                uname = c.UserName;
                pid = c.Pid;
                areaid = dic.ContainsKey("agentid") ? dic["agentid"] : "";

                area = GetCityName(areaid);
            }
            Traning_NetworkMeeting_Query query = new Traning_NetworkMeeting_Query();
            List<Traning_NetworkMeeting> list = new List<Traning_NetworkMeeting>();
            Traning_NetworkMeetingBLL bll = new Traning_NetworkMeetingBLL();
            list = bll.GetMonthLst(query);
            if (pid == "121")//睿讯通(读睿讯通网络会议和其他版本会议）
            {
                list = list.Where(x => x.chblist_pro.Contains(pid)).OrderBy(x => x.class_date).ToList();
            }
            else//（只能读处睿讯通以外的会议）
            {
                list = list.Where(x => x.chblist_pro != "121").OrderBy(x => x.class_date).ToList();
            }
            int page = 1;
            if (!int.TryParse(Request["page"], out page))
            {
                page = 1;
            }
            int count = list.Count;
            list = list.Skip((page - 1) * 9).Take(9).ToList();
            string strPage = StringTools.PageUrlWeb(count, page, 9, "?" + url);
            ViewData["strPage"] = strPage;
            ViewData["lst"] = list;
            ViewData["url"] = url;
            ViewData["uname"] = uname;
            ViewData["area"] = area;
            ViewData["pid"] = pid;
            ViewBag.uid = uid;
            return View();
        }

        public ActionResult GetReservenum_dm()
        {
            string placenum = Request["placenum"];
            string uid = Request["uid"];
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var c = GetUser(ref dic,uid);
            List<Web_TrainUser> wtulst = new List<Web_TrainUser>();
            Web_TrainUserBLL wtubll = new Web_TrainUserBLL();
            
            if (!string.IsNullOrEmpty(c.UserName))
            {
                wtulst = wtubll.GetListByMonth(c.UserName);
            }
            wtulst = wtulst.Where(x => x.place_num == placenum).ToList();
            string code = "";
            if (wtulst.Count > 0)
            {
                code = wtulst[0].reserve_num;
            }
            return Content(code);
        }


        public ActionResult zlzjtrain()
        {
            string uid = Request["uid"];
            ViewBag.uid = uid;
            return View();
        }
    }
}
